﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace PainterControl
{
    public class PluginManager
    {
        public delegate void loadEvent(IPainter ui);
        public event loadEvent loadUIEvent;

        List<Assembly> assemblyList;
        List<Type> assemblyTypeList;
        List<Object> assemblyObjetList;

        public PluginManager()
        {
            try
            {
                if (!Directory.Exists("plugin")) Directory.CreateDirectory("plugin");
                string[] file = Directory.GetFiles("plugin", "*.dll");
                assemblyList = file.Select(o => Assembly.LoadFile(new DirectoryInfo(o).FullName)).
                    Where(o => o.ManifestModule.ToString().ToLower() != "paintercontrol.dll")
                    .Where(o=>o.GetTypes().Any(t=>t.GetInterface("IPainter")!=null)).ToList();
                assemblyTypeList = assemblyList.Select(o => o.GetTypes()).SelectMany(o=>o).ToList();
                assemblyObjetList = assemblyTypeList.Select(o => o.Assembly.CreateInstance(o.FullName))
                    .Where(o => o is IPainter).ToList();
            }
            catch { }
        }
        public void load()
        {
            assemblyObjetList.ForEach(o => {
                if (loadUIEvent != null) loadUIEvent(o as IPainter);
            });
        }
    }
}
